package com.wanke.utils;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Scanner;

/**
 * @program: jpa_demo
 * @ClassName SshTest
 * @author: WXK
 * @create: 2024-08-25 19:12
 **/
public class SshTest {

    private static JSch jsch;
    public static Session session;

    public static ChannelExec channel;


    /**
     * 连接到指定的IP
     *
     * @throws JSchException
     */
    public static void connect(String user, String passwd, String host, int port) throws JSchException {
        jsch = new JSch();// 创建JSch对象
        session = jsch.getSession(user, host, port);// 根据用户名、主机ip、端口号获取一个Session对象
        session.setPassword(passwd);// 设置密码

        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);// 为Session对象设置properties
        session.setTimeout(1500);// 设置超时
        session.connect();// 通过Session建立连接
        channel = (ChannelExec) session.openChannel("exec");
    }




    public static void execCmd(String command) throws JSchException {
        BufferedReader reader = null;
        Channel channel = null;
        try {
            if (command != null) {
                channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand(command);
                ((ChannelExec) channel).setErrStream(System.err);
                channel.connect();

                InputStream in = channel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                String buf = null;
                while ((buf = reader.readLine()) != null) {
                    System.out.println(buf+"------------------");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
//        finally {
//            try {
//                reader.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        channel.disconnect();
    }


    public static void close() {
        session.disconnect();
    }



    public static void main(String[] args) {
        try {
            // 1.连接到指定的服务器
            connect("root", "root", "192.168.150.106", 22);

            // 2.执行相关的命令
//            execCmd("mkdir /home/data");
//          创建Scanner对象来读取用户输入
            String nextLine;
            do {
                Scanner scanner = new Scanner(System.in);
                System.out.println("输入要执行的操作命令");
                nextLine = scanner.nextLine();
                execCmd(nextLine);
            } while (!nextLine.equals("1"));

            // 3.下载文件
            //  download("/home/zyl.txt", "F:\\tmp");

            // 4.关闭连接
                close();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

}



